package service

import (
	"errors"
	//"github.com/SkyAPM/go2sky"
	//"github.com/SkyAPM/go2sky/reporter"
	//"github.com/micro/go-micro/v2"
	"strings"

	"github.com/micro/go-micro/v2/config/cmd"
	"github.com/micro/go-micro/v2/web"

	"hmsDemo/hms.api/config"
	"hmsDemo/hms.api/webhandler"

	"github.com/micro/go-micro/v2/registry"

	"gitee.com/tgodfather/go-plugins/serviceparam"

	log "gitee.com/tgodfather/misc/logger"

	"go.uber.org/zap"
)

func checkApiGatewayCfg(cfg *config.ServiceConfig) error {
	if 2 > len(cfg.ServerAddress) || strings.Contains(cfg.ServerAddress, "$") {
		return errors.New("Invalid ServerAddress :" + cfg.ServerAddress)
	}
	if 2 > len(cfg.RegistryType) || strings.Contains(cfg.RegistryType, "$") {
		return errors.New("Invalid RegistryType :" + cfg.RegistryType)
	}
	if 2 > len(cfg.RegistryAddress) || strings.Contains(cfg.RegistryAddress, "$") {
		return errors.New("Invalid RegistryAddress :" + cfg.RegistryAddress)
	}

	return nil
}

func ApiGateway(cfg *config.ServiceConfig, ver string) {

	//servceId := strings.ToLower(cfg.ID)
	serviceName := strings.ToLower(cfg.ServiceName)
	log.Info("Init", zap.String("serviceType", cfg.ServiceType),
		zap.String("serviceName", cfg.ServiceName),
		zap.String("version", ver))
	//检查配置, 判断长度
	err := checkApiGatewayCfg(cfg)
	if nil != err {
		log.Fatal("config check Error", zap.Error(err))
		return
	} else {
		log.Info("config check valid", zap.Reflect("configs", cfg))
	}
	// New Service

	//registry param
	//服务注册的参数, 以nacos开头的参数，其实应该改为sr开头更合适，表示服务注册

	regParam := map[string]string{
		//"regGroup": "hms",  //注册的 group Name  apigateway 的group 为 default_group
		//"regNS": "cde", //注册的 namespace
		//"regCluster": "",   //注册的 cluster Name
		"watchGroup": "hms", //监听的group，默认为regGroup
		//"watchCluster":  "hms",  //监听的group，regCluster
	}
	f := func(key, value string) bool {
		//只支持 a.b 的参数名， 不支持 a.b.c
		arrayKey := strings.Split(key, "_")
		if 2 == len(arrayKey) {

			if "registry" == arrayKey[0] {
				paramName := arrayKey[1]
				regParam[paramName] = value
				log.Info("Config Registry Param",
					zap.String("key", paramName),
					zap.String("value", value))
			}
		}
		return false // 返回false 表示 继续
	}
	cfg.WalkParams(f)

	log.Info("service init config",
		zap.String("ServerAddress", cfg.ServerAddress),
		zap.String("ServerAdvertise", cfg.ServerAdvertise),
		zap.String("RegistryAddress", cfg.RegistryAddress))

	//tracer := TraceBoot("192.168.0.191:11800", cfg.ServiceName)
	//microService := micro.NewService(
	//	micro.WrapClient(wrapperTrace.NewClientWrapper(tracer)),
	//	micro.WrapHandler(wrapperTrace.NewHandlerWrapper(tracer)),
	//	micro.WrapCall(wrapperTrace.NewCallWrapper(tracer)),
	//	//micro.WrapSubscriber(wrapperTrace.NewSubscriberWrapper(tracer)),
	//	)

	// create new web service
	service := web.NewService(
		web.Name(serviceName),
		web.Version(ver),
		web.Address(cfg.ServerAddress),
		web.Advertise(cfg.ServerAdvertise),
		//web.Registry(zookeeper.NewRegistry(registry.Addrs(cfg.RegistryAddress))),
		web.Registry(cmd.DefaultRegistries[cfg.RegistryType](
			registry.Addrs(cfg.RegistryAddress),
			serviceparam.ContextParam(regParam)),
		),
		//web.MicroService(microService),
	)

	//micro.WrapHandler()
	service.Init()
	log.Info("service init Success")
	//log.Error("Check serivce Client", zap.Reflect("c", service.Client()), zap.Bool("b", bClient))

	//hms.RegisterVpaaSServiceHandler(service.Server(), handler.NewVpaasImageHandler(cfg))
	setImageHandler(service, cfg)

	log.Info("start to run service")
	// Run service
	if err := service.Run(); err != nil {
		log.Fatal("Service Run Fail", zap.Error(err))
	}

}

func setImageHandler(service web.Service, cfg *config.ServiceConfig) {

	wc := webhandler.GetWebCenter()
	wc.Init(cfg)
	//h:= webhandler.GetHttpHandler()

	service.Handle("/", wc.GetHttpHandler())
	//app.Logger()
}
